package com.featherlike.feather.generator.engine;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.featherlike.feather.generator.config.Constant;
import com.featherlike.framework.common.util.ClassUtil;
import com.featherlike.framework.common.util.Exceptions;
import com.featherlike.framework.common.util.FileUtil;
import com.featherlike.framework.common.util.IOUtil;
import com.featherlike.framework.common.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * @author WYY
 * @description
 */
public class FreeMarkerImpl implements ITemplateEngine {
    /**Log**/
    private static final Logger LOGGER = LoggerFactory.getLogger(VelocityImpl.class);
    /**Configuration**/
    private static final Configuration CFG = new Configuration();

    public FreeMarkerImpl(String tmplPath) {
        try {
            if (StringUtil.isEmpty(tmplPath)) {
                CFG.setDirectoryForTemplateLoading(new File(ClassUtil.getClassPath()));
            } else {
                CFG.setDirectoryForTemplateLoading(new File(tmplPath));
            }
            CFG.setDefaultEncoding(Constant.ENCODING_UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void mergeTemplateIntoFile(String ftlPath, Map<String, Object> model, String filePath) {
        FileWriter writer = null;
        try {
            if (FileUtil.createFile(filePath)) {
                Template template = CFG.getTemplate(ftlPath);
                writer = new FileWriter(filePath);
                template.process(model, writer);
            } else {
                LOGGER.info("文件已存在,生成失败");
            }
        } catch (Exception e) {
            LOGGER.error("合并模板出错！", e);
            throw Exceptions.unchecked(e);
        } finally {
            IOUtil.closeQuietly(writer);
        }
    }

    @Override
    public String mergeTemplateReturnString(String ftlPath,
            Map<String, Object> model) {
        String result;
        StringWriter writer = null;
        try {
            Template template = CFG.getTemplate(ftlPath);
            writer = new StringWriter();
            template.process(model, writer);
            result = writer.toString();
            writer.close();
        } catch (Exception e) {
            LOGGER.error("合并模板出错！", e);
            throw Exceptions.unchecked(e);
        } finally {
            IOUtil.closeQuietly(writer);
        }

        return result;
    }

    @Override
    public String getTemplateSuffix() {
        return Constant.ENGINE_FTL_SURFIX;
    }
}
